'use strict';

const {
	verifyToken
} = require("wx-common");

exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)

	const db = uniCloud.database();
	const dbCmd = db.command;

	const payload = event.token ? verifyToken(event.token) : null;

	//actions

	const action = event.action; //create, query, update, delete

	let dbRes;

	if (action === "create") {
		//内容安全检查

		//创建书架
		dbRes = await db.collection("bookshelfs").add({
			owner: payload.openid,
			name: event.name,
			address: event.address,
			geopoint: new db.Geo.Point(event.longitude, event.latitude),
			totalbook: 0
		});
	} else if (action === "listmy") {
		dbRes = await db.collection("bookshelfs").where({ //所有通过where查询的字段，都应该增加索引以提高性能
				owner: dbCmd.eq(payload.openid)
			})
			.orderBy("_id", "desc")
			.limit(10) //limit skip 配合可以实现翻页
			.get();
	} else if (action === "delete") {
		dbRes = await db.collection("bookshelfs").where({
			"_id": dbCmd.eq(event._id),
			"owner": dbCmd.eq(payload.openid)
		}).remove()
		if (dbRes.deleted === 0) {
			console.log("请检查数据库表名是否正确")
		}
	} else if (action === "get") {
		dbRes = await db.collection("bookshelfs").where({
				"_id": dbCmd.eq(event._id)
			})
			.limit(1) //其实是多余的，因为"_id"是唯一的
			.get();

		const owner = dbRes.data[0]["owner"];
		delete dbRes.data[0]["owner"]; //不能保留openid

		dbRes.data[0]["isowner"] = payload ? owner === payload.openid : false;

		const ownerinfo = await db.collection("users").field({
			openid: false
		}).where({
			openid: dbCmd.eq(owner)
		}).get();

		dbRes.data[0]["ownerinfo"] = ownerinfo.data[0];

		return dbRes.data[0];
	} else if (action === "listbygeo") {
		dbRes = await db.collection("bookshelfs").where({
				geopoint: dbCmd.geoNear({
					geometry: new db.Geo.Point(event.longitude, event.latitude),
					maxDistance: 1000, //单位是米，中心点是地图视野中心点
					minDistance: 0
				})
			})
			.limit(100)
			.get();
	} else if (action === "update") {
		dbRes = await db.collection("bookshelfs").where({
			"_id": dbCmd.eq(event._id),
			"owner": dbCmd.eq(payload.openid)
		}).limit(1).update({
			name: event.name,
			address: event.address,
			geopoint: new db.Geo.Point(event.longitude, event.latitude)
		});
	}

	//返回数据给客户端
	return dbRes.data;
};
